package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.service.ScheduleTaskActionService;
import com.xbongbong.schedule.pojo.dto.ScheduleTaskActionDTO;
import com.xbongbong.schedule.pojo.vo.ScheduleTaskActionVO;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Locale;
import java.util.Objects;

@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/schedule/task")
public class ScheduleTaskActionController {

    @Resource
    private ScheduleTaskActionService scheduleTaskActionService;

    @RequestMapping(value = "/action", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String scheduleTaskAction(@RequestBody @Valid ScheduleTaskActionDTO scheduleTaskCancelDTO, BindingResult br, @RequestParam("lang") String lang) {
        LocaleContextHolder.setLocale(Locale.SIMPLIFIED_CHINESE);
        if (!Objects.equals(lang, Locale.SIMPLIFIED_CHINESE.toString())) {
            LocaleContextHolder.setLocale(Locale.US);
        }
        XbbResponse<ScheduleTaskActionVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ScheduleTaskActionVO scheduleTaskActionVO = scheduleTaskActionService.scheduleTaskAction(scheduleTaskCancelDTO);
                response = new XbbResponse<>(scheduleTaskActionVO);
            } catch (XbbException xbbException) {
                response = new XbbResponse<>(xbbException);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
}
